package com.smartapp.update;

import java.io.File;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.Iterator;
import java.util.List;

import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.pm.Signature;
import android.net.Uri;
import android.os.Build;
import android.support.v4.content.FileProvider;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.util.Log;


//import com.vondear.rxtools.RxFileTool;

public class Utils {
	/**
	 * 获取已安装Apk文件的源Apk文件 如：/data/app/com.smartapp.update.SmartAppUpdate.apk
	 * 
	 * @param context
	 * @param packageName
	 * @return
	 */
	public static String getSourceApkPath(Context context, String packageName) {
		if (TextUtils.isEmpty(packageName))
			return null;
		try {
			ApplicationInfo appInfo = context.getPackageManager()
					.getApplicationInfo(packageName, 0);
			return appInfo.sourceDir;
		} catch (NameNotFoundException e) {
			e.printStackTrace();
		}

		return null;
	}

	/**
	 * 安装Apk
	 * 
	 * @param context
	 * @param apkPath
	 */
	public static void installApk(Context context, String apkPath) {
//		Intent intent = new Intent(Intent.ACTION_VIEW);
//		intent.setDataAndType(Uri.parse("file://" + apkPath),
//				"application/vnd.android.package-archive");
//		context.startActivity(intent);

//		Intent intent = new Intent(Intent.ACTION_VIEW);
//		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
//			intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
//			Uri contentUri = FileProvider.getUriForFile(context, "com.smartapp.update.fileprovider", new File(apkPath));
//			intent.setDataAndType(contentUri, "application/vnd.android.package-archive");
//		} else {
//			intent.setDataAndType(Uri.fromFile(new File(apkPath)), "application/vnd.android.package-archive");
//			intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//		}
//		context.startActivity(intent);

		Intent i = new Intent(Intent.ACTION_VIEW);
		if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.N){
			i.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
			Uri contentUri = FileProvider.getUriForFile(context, BuildConfig.APPLICATION_ID + ".fileprovider", new File(apkPath));
			i.setDataAndType(contentUri, "application/vnd.android.package-archive");
		}else {
			i.setDataAndType(Uri.parse("file://" + apkPath), "application/vnd.android.package-archive");
		}
		context.startActivity(i);

//		File apkfile = new File(apkPath);
//		if (!apkfile.exists()) {
//			return;
//		}
//		Intent intent = new Intent(Intent.ACTION_VIEW);
////		Uri contentUri = RxFileTool.getUriForFile(context, apkfile);
//
//		Uri contentUri = null;
//		if (Build.VERSION.SDK_INT >= 24) {
//			contentUri = FileProvider.getUriForFile(context, context.getPackageName() + ".fileprovider", apkfile);
//			Log.e("contentUri===", "==="+contentUri);
//		} else {
//			contentUri = Uri.fromFile(apkfile);
//		}
//
////		intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
//			intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
//		}
//		intent.setDataAndType(contentUri, "application/vnd.android.package-archive");
//		context.startActivity(intent);
	}

	/**
	 * 获取未安装Apk的签名
	 * 
	 * @param apkPath
	 * @return
	 */
	public static String getUnInstalledApkSignature(String apkPath) {
		String PATH_PackageParser = "android.content.pm.PackageParser";
		try {
			Class<?> pkgParserCls = Class.forName(PATH_PackageParser);
			Class<?>[] typeArgs = new Class[1];
			typeArgs[0] = String.class;
			Constructor<?> pkgParserCt = pkgParserCls.getConstructor(typeArgs);
			Object[] valueArgs = new Object[1];
			valueArgs[0] = apkPath;
			Object pkgParser = pkgParserCt.newInstance(valueArgs);

			DisplayMetrics metrics = new DisplayMetrics();
			metrics.setToDefaults();

			typeArgs = new Class[4];
			typeArgs[0] = File.class;
			typeArgs[1] = String.class;
			typeArgs[2] = DisplayMetrics.class;
			typeArgs[3] = Integer.TYPE;

			Method pkgParser_parsePackageMtd = pkgParserCls.getDeclaredMethod(
					"parsePackage", typeArgs);
			valueArgs = new Object[4];
			valueArgs[0] = new File(apkPath);
			valueArgs[1] = apkPath;
			valueArgs[2] = metrics;
			valueArgs[3] = PackageManager.GET_SIGNATURES;
			Object pkgParserPkg = pkgParser_parsePackageMtd.invoke(pkgParser,
					valueArgs);

			typeArgs = new Class[2];
			typeArgs[0] = pkgParserPkg.getClass();
			typeArgs[1] = Integer.TYPE;

			Method pkgParser_collectCertificatesMtd = pkgParserCls
					.getDeclaredMethod("collectCertificates", typeArgs);
			valueArgs = new Object[2];
			valueArgs[0] = pkgParserPkg;
			valueArgs[1] = PackageManager.GET_SIGNATURES;
			pkgParser_collectCertificatesMtd.invoke(pkgParser, valueArgs);

			Field packageInfoFld = pkgParserPkg.getClass().getDeclaredField(
					"mSignatures");
			Signature[] info = (Signature[]) packageInfoFld.get(pkgParserPkg);
			return info[0].toCharsString();
		} catch (Exception e) {
			e.printStackTrace();
		}

		return null;
	}

	/**
	 * 获取已安装apk签名
	 * 
	 * @param context
	 * @param packageName
	 * @return
	 */
	public static String getInstalledApkSignature(Context context,
			String packageName) {
		PackageManager pm = context.getPackageManager();
		List<PackageInfo> apps = pm
				.getInstalledPackages(PackageManager.GET_SIGNATURES);

		Iterator<PackageInfo> iter = apps.iterator();
		while (iter.hasNext()) {
			PackageInfo packageinfo = iter.next();
			String thisName = packageinfo.packageName;
			if (thisName.equals(packageName)) {
				return packageinfo.signatures[0].toCharsString();
			}
		}

		return null;
	}
}
